package org.sean.contactdemo.util;

import java.util.Iterator;
import java.util.Map;
import java.util.HashMap;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.plugin.AbstractUIPlugin;

public class ImageCache {

	private final Map<String, Image> imageMap = new HashMap<String, Image>();
	private static ImageCache INSTANCE = new ImageCache();

	private ImageCache() {
	}

	public static ImageCache getINSTANCE() {
		return INSTANCE;
	}

	public Image getImage(String applicationID, String imageName) {
		if (imageName == null) {
			return Display.getCurrent().getSystemImage(SWT.ICON_ERROR);
		}
		Image image = (Image) imageMap.get(imageName);
		if (image == null) {
			try {
				image = AbstractUIPlugin.imageDescriptorFromPlugin(
						applicationID, imageName).createImage();
			} catch (Exception e) {
				image = Display.getCurrent().getSystemImage(SWT.ICON_ERROR);
			}
			imageMap.put(imageName, image);
		}
		return image;
	}

	public void dispose() {
		Iterator<Image> iterator = imageMap.values().iterator();
		while (iterator.hasNext()) {
			((Image) iterator.next()).dispose();
		}
		imageMap.clear();
	}

	public Image getLocalImage(String imageName) {
		return this.getImage(APPConstants.APPLICATION_ID, imageName);
	}
}
